package com.optimize.project.netCache;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ImageView;

import com.optimize.project.R;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * DiskCache使用测试
 */
public class DiskCacheTestActivity extends Activity {
    private String cache_key = "cache_img";
    private String cache_text = "cache_text";
    private DiskCacheManager diskCacheManager;
    private String imgUrl = "http://img2.pconline.com.cn/pconline/0706/19/1038447_34.jpg";
    private ExecutorService  executorService = Executors.newSingleThreadExecutor();
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0x21:
                    Bitmap  bitmap = diskCacheManager.getBitmap(cache_key);
                    if (null != bitmap){
                        imageView.setImageBitmap(bitmap);
                    }
                    break;
            }
        }
    } ;
    private DiskLruCache diskLruCache;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_disk_cache_test);
        diskCacheManager = DiskCacheManager.getInstance(this);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE},0x45);
        }else {
            execute();
        }

    }

    private void execute() {
        diskLruCache = diskCacheManager.open();
        final DiskLruCache.Editor editor = diskCacheManager.editor(cache_key);
        imageView = findViewById(R.id.img_cache);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                if (null != diskCacheManager.newOS(editor,0)){
                    boolean sucess =  downloadUrlToStream(imgUrl,diskCacheManager.newOS(editor,0));
                    if (sucess){
                        diskCacheManager.commit(editor);
                        handler.sendEmptyMessage(0x21);
                    }else {
                        diskCacheManager.abort(editor);
                    }
                }
            }
        });
    }


    @Override
    protected void onPause() {
        if (null != diskCacheManager){
            diskCacheManager.flush();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (null != diskCacheManager){
            diskCacheManager.close();
        }
        executorService.shutdown();
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x45){
            if (grantResults[0] == 0 && grantResults[1] == 0){
                execute();
            }
        }
    }

    /**
     * 下载图片
     * @param urlString
     * @param outputStream
     * @return
     */
    private boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream());
            out = new BufferedOutputStream(outputStream);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (Exception e) {
            Log.e(DiskCacheTestActivity.class.getName(), "Error in downloadBitmap - " + e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                Log.e(DiskCacheTestActivity.class.getName(), "Error in downloadBitmap - " + e);
            }
        }
        return false;
    }

}
